package com.qst.beans;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class Cart {
    private Map<Integer, CartItem> map = new LinkedHashMap<>();
    private double total;
    private Collection<CartItem> cartItems;

    public Cart(){}

    /*得到所有的购物项*/
    public Collection<CartItem> getCartItems(){
        return  map.values();
    }

    //从购物车移除购物项
    public void removeItemCart(Integer pid){
//        total -= map.get(pid).getSubtotal();
        CartItem removeItem = map.remove(pid);
        this.total -= removeItem.getSubtotal();
    }
    //清空购物车
    public void clearCart(){
        map.clear();
        this.total = 0;
    }
    //添加购物项
    public void addItemCart(CartItem cartItem){
        Integer pid = cartItem.getProduct().getPid();
        if(map.containsKey(pid)){
            /*已经存在，数量增加
                    总计增加*/
            CartItem cartItemOne = map.get(pid);
            cartItemOne.setCount(cartItemOne.getCount()+1);
//            this.total += cartItemOne.getSubtotal();
        }else {
            map.put(pid,cartItem);
        }
        total += cartItem.getSubtotal();
    }
    //得到购物总计
    public Double getTotal(){
        return this.total;
    }
}
